/*
 * PhonemapUtil.java
 */
package com.phonemap.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import com.phonemap.math.LatLng;
import com.phonemap.math.LatLngTool;
import com.phonemap.math.LengthUnit;

/**
 * The Class PhonemapUtil.
 */
public final class PhonemapUtil {
	
	/** The Constant ROTATED_DEGREE. */
	public static final double ROTATED_DEGREE = 90;
	
	/** The Constant R. */
	public static final double R = 0.100;
	
	/**
	 * Instantiates a new phonemap util.
	 */
	private PhonemapUtil() {
		
	}
	
	/**
	 * Gets the positions.
	 *
	 * @param filename the filename
	 * @return the positions
	 */
	public static List<LatLng> getPositions(final String filename) {
		List<LatLng> positions = new ArrayList<LatLng>();

		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(filename));
			String line = br.readLine();

			while (line != null) {
				String[] point = line.split(",");
				positions.add(new LatLng(Double.parseDouble(point[0]), Double.parseDouble(point[1])));
				line = br.readLine();
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return positions;
	}
	 
	/**
	 * Checks if is inside.
	 *
	 * @param value the value
	 * @param num1 the num1
	 * @param num2 the num2
	 * @return true, if is inside
	 */
	public static boolean isInside(final double value, final double num1, final double num2) {
		if (num1 < num2) {
			if (value > num1 && value < num2) {
				return true;
			}
		} else {
			if (value <= num1 && value >= num2) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Checks if is inside.
	 *
	 * @param mid the mid
	 * @param start the start
	 * @param end the end
	 * @return true, if is inside
	 */
	public static boolean isInside(final LatLng mid, final LatLng start, final LatLng end) {
		double bearing = LatLngTool.initialBearing(start, end);
		LatLng pRight = LatLngTool.travel(start, bearing + ROTATED_DEGREE, R,
				LengthUnit.KILOMETER);
		LatLng pLeft = LatLngTool.travel(start, bearing - ROTATED_DEGREE, R,
				LengthUnit.KILOMETER);
		double dist = LatLngTool.distance(start, mid, LengthUnit.KILOMETER);
		
		pRight = LatLngTool.travel(pRight, bearing, dist,
				LengthUnit.KILOMETER);
		pLeft = LatLngTool.travel(pLeft, bearing, dist,
				LengthUnit.KILOMETER);
		
		return !(PhonemapUtil.isInside(mid.getLatitude(),
				pLeft.getLatitude(), pRight.getLatitude())
				&& PhonemapUtil.isInside(mid.getLongitude(),
						pLeft.getLongitude(), pRight.getLongitude()));
	}

}
